package com.ja.openchat.ui.found;

import android.content.pm.ActivityInfo;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.dueeeke.videoplayer.player.VideoView;
import com.dueeeke.videoplayer.player.VideoViewManager;
import com.google.gson.JsonObject;
import com.ja.openchat.R;
import com.ja.openchat.adapters.CircleHomeAdapter;
import com.ja.openchat.adapters.CircleHomeViewHolder;
import com.ja.openchat.views.Utils;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.circle.BlogInfo;
import com.zy.openchat.core.model.circle.BlogListInfo;
import com.zy.openchat.core.model.circle.BlogReplyInfo;
import com.zy.openchat.core.model.circle.BlogUserInfo;
import com.zy.openchat.core.model.circle.CircleVisibleType;
import com.zy.openchat.core.model.file.FileInfo;
import com.zy.openchat.core.model.file.FileTaskInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.core.model.video.VideoInfo;
import com.zy.openchat.util.Common;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.goldze.mvvmhabit.base.BaseViewModel;

import static androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_IDLE;

public class CircleHomeFragment extends AbsCircleFragment<MultiItemEntity, CircleHomeViewHolder> {

    public static CircleHomeFragment newInstance(@IntRange(from = 0,to = 2) int recordType,String topicId){
        CircleHomeFragment fragment = new CircleHomeFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type",recordType);
        if(!TextUtils.isEmpty(topicId)){
            bundle.putString("topicId",topicId);
        }
        fragment.setArguments(bundle);
        return fragment;
    }

    public static CircleHomeFragment newInstance(@IntRange(from = 0,to = 2) int recordType){
        return newInstance(recordType,null);
    }

    private int mType;

    /**
     * 当前播放的位置
     */
    protected int mCurPos = -1;
    /**
     * 上次播放的位置，用于页面切回来之后恢复播放
     */
    protected int mLastPos = mCurPos;
    private String mTopicId = null;

    @Override
    protected void initView(View view) {
        if(getArguments()!=null){
            mType = getArguments().getInt("type");
            mTopicId = getArguments().getString("topicId");
        }
        super.initView(view);
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                MultiItemEntity multiItemEntity = mAdapter.getItem(position);
                if(multiItemEntity!=null&&multiItemEntity instanceof BlogInfo){
                    CircleDetailActivity.startDetail(getContext(),((BlogInfo)multiItemEntity).id);
                }

            }
        });
        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                if(view.getId() == R.id.post_content){
                    mAdapter.getOnItemClickListener().onItemClick(adapter,view,position);
                }else{
                    ((CircleHomeAdapter)mAdapter).onItemChildClick(adapter,view,position);
                }


            }
        });
        ((CircleHomeAdapter)mAdapter).setPreviewMediaClickListener(new OnPreviewMediaClickListener() {
            @Override
            public void onPreviewMediaClick(int blogIndex, int mediaIndex) {
                doPreviewMediaClick(blogIndex,mediaIndex);
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == SCROLL_STATE_IDLE) { //滚动停止
                    autoPlayVideo(recyclerView);
                }
            }

            private void autoPlayVideo(RecyclerView view) {
                if (view == null) return;
                //遍历RecyclerView子控件,如果mPlayerContainer完全可见就开始播放
                int count = view.getChildCount();
                for (int i = 0; i < count; i++) {
                    View itemView = view.getChildAt(i);
                    if (itemView == null) continue;
                    CircleHomeViewHolder holder = (CircleHomeViewHolder) itemView.getTag();
                    MultiItemEntity multiItemEntity = mAdapter.getItem(holder.getAdapterPosition());
                    if(holder.mPlayerContainer!=null&&multiItemEntity!=null&&multiItemEntity instanceof BlogInfo&&((BlogInfo)multiItemEntity).isVideoType()){
                        Rect rect = new Rect();
                        holder.mPlayerContainer.getLocalVisibleRect(rect);
                        int height = holder.mPlayerContainer.getHeight();
                        if (rect.top == 0 && rect.bottom == height) {
                            startPlay(holder.getAdapterPosition());
                            break;
                        }
                    }

                }
            }
        });
    }

    private void doPreviewMediaClick(int blogIndex, int mediaIndex){
        CircleVerticalActivity.start(getContext(),mType,mBlogInfos,blogIndex,mediaIndex,currentPage);
    }
    protected void startPlay(int position) {
        if (mCurPos == position) return;
        if (mCurPos != -1) {
            releaseVideoView();
        }
        MultiItemEntity multiItemEntity = mAdapter.getItem(position);
        if(multiItemEntity!=null&&multiItemEntity instanceof BlogInfo&&((BlogInfo)multiItemEntity).isVideoType()){
            BlogInfo blogInfo = (BlogInfo)multiItemEntity;
            VideoInfo videoInfo = ((BlogInfo)multiItemEntity).content.video;
            if(mVideoView==null){
                initVideoView();
            }
            mVideoView.setUrl(videoInfo.localVideoPath());
            View itemView = mLinearLayoutManager.findViewByPosition(position);
            if (itemView == null) return;
            CircleHomeViewHolder viewHolder = (CircleHomeViewHolder) itemView.getTag();
            if(viewHolder.mPrepareView==null||viewHolder.mPlayerContainer==null) return;
            mController.setOnClick(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    doPreviewMediaClick(position,0);
                }
            });
            mController.addControlComponent(viewHolder.mPrepareView, true);
            Utils.removeViewFormParent(mVideoView);
            viewHolder.mPlayerContainer.addView(mVideoView, 0);
            //播放之前将VideoView添加到VideoViewManager以便在别的页面也能操作它
            getVideoViewManager().add(mVideoView, "list");
            mVideoView.start();
            mCurPos = position;
        }

    }

    protected VideoViewManager getVideoViewManager() {
        return VideoViewManager.instance();
    }


    private void releaseVideoView() {
        if(mVideoView==null){
            return;
        }
        mVideoView.release();
        if (mVideoView.isFullScreen()) {
            mVideoView.stopFullScreen();
        }
        if(getActivity().getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        mCurPos = -1;
    }

    @Override
    public void onFragmentPause() {
        super.onFragmentPause();
        releaseVideoView();
    }

    private void resume() {
        if (mLastPos == -1)
            return;
        //恢复上次播放的位置
        startPlay(mLastPos);
    }

    @Override
    protected int initLayout() {
        return R.layout.fragment_circle_home;
    }

    @Override
    protected BaseQuickAdapter<MultiItemEntity, CircleHomeViewHolder> newIntanceAdapter() {
        BaseViewModel viewModel = ViewModelProviders.of(getActivity()).get(BaseViewModel.class);
        return new CircleHomeAdapter(mType, null, viewModel);
    }

    private long getLastBlogId(int page){
        if(page==1){
            return 0;
        }else{
            return ((BlogInfo)mAdapter.getItem(mAdapter.getData().size()-1)).id;
        }
    }
    private ArrayList<BlogInfo> mBlogInfos = new ArrayList<>();
    @Override
    protected void requestData(int page) {
        if(page>1&&Common.isEmpty(mAdapter.getData())){
            return;
        }
        releaseVideoView();
        TelegramManager.getTelegramManager().getCircleHistory(getContext(), new CircleVisibleType(mType,mTopicId), getLastBlogId(page) ,20, new TgResultBlock<BlogListInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, BlogListInfo obj) {
                if(page==1){
                    mBlogInfos.clear();
                }
                List<MultiItemEntity> circleInfos = new ArrayList<>();
                if (!Common.isEmpty(obj.blogs)) {
                    mBlogInfos.addAll(obj.blogs);
                    circleInfos.addAll(obj.blogs);
                }
                finishRefreshAndLoad(page, circleInfos);
                if (getActivity() != null && getActivity() instanceof OnCirclePagerListener) {
                    if (((OnCirclePagerListener) getActivity()).getCurrentIndex() == mType) {
                        recyclerView.post(new Runnable() {
                            @Override
                            public void run() {
                                startPlay(0);
                            }
                        });
                    }
                }
            }


            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }


    protected VideoView mVideoView;
    protected CircleStandardVideoController mController;
    protected void initVideoView() {
        mVideoView = new VideoView(getActivity());
        mVideoView.setLooping(true);
//        mVideoView.setOnStateChangeListener(new VideoView.SimpleOnStateChangeListener() {
//            @Override
//            public void onPlayStateChanged(int playState) {
//                if (playState == VideoView.STATE_IDLE) {
//                    Utils.removeViewFormParent(mVideoView);
//                    mLastPos = mCurPos;
//                    mCurPos = -1;
//                }
//            }
//        });
        mController = new CircleStandardVideoController(getActivity());
        mController.setEnableOrientation(false);
        mVideoView.setVideoController(mController);
    }

    @Override
    protected boolean isHaveEventBus() {
        return true;
    }

    @Override
    public void onTgEvent(TgEvent tg_event) {
        if (tg_event == null) {
            return;
        }
        switch (tg_event.event) {
            case ECircle_Send_Blog_Success:
                onRefresh();
                break;
            case ECircle_Like_Update:
                if(tg_event.data!=null){
                    if(tg_event.data instanceof BlogInfo){
                        BlogInfo blogInfo = (BlogInfo) tg_event.data;
                        ((CircleHomeAdapter)mAdapter).notifyLike(blogInfo);
                    }
                }
                break;
            case ECircle_Follow_Update:
                if(tg_event.data!=null&&tg_event.data instanceof BlogUserInfo){
                    BlogUserInfo blogUserInfo = (BlogUserInfo) tg_event.data;
                    ((CircleHomeAdapter)mAdapter).updateBlogUserInfo(blogUserInfo);
                }
                break;
            case ECircle_Add_Reply:
                if(tg_event.data!=null&&tg_event.data instanceof BlogReplyInfo){
                    BlogReplyInfo blogReplyInfo = (BlogReplyInfo) tg_event.data;
                    ((CircleHomeAdapter)mAdapter).notifyComment(blogReplyInfo);
                }
                break;
            case EUser_Td_Delete_Blog:
                if(tg_event.data!=null&&tg_event.data instanceof Long){
                    long blogId = (Long) tg_event.data;
                    ((CircleHomeAdapter)mAdapter).removeBlog(blogId);
                }
                break;
            case EUser_Td_Contact_Photo_Ok:
            case EUser_Td_UpdateContactInfo:
                if ((tg_event.data instanceof UserInfo)) {
                    UserInfo userInfo = (UserInfo) tg_event.data;
                    Observable.create(new ObservableOnSubscribe<DiffUtil.DiffResult>() {
                        @Override
                        public void subscribe(ObservableEmitter<DiffUtil.DiffResult> e) {
                            DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new BlogAvatarDiffCallBack(mAdapter.getData(), mAdapter.getData()), false);
                            e.onNext(diffResult);
                        }
                    }).subscribeOn(Schedulers.computation())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Consumer<DiffUtil.DiffResult>() {
                                @Override
                                public void accept(DiffUtil.DiffResult diffResult) {
                                    diffResult.dispatchUpdatesTo(mAdapter);
                                }
                            });
                }
            case EUser_Td_Message_Photo_Ok:
            case EUser_Td_Message_Video_Ok:
                if(tg_event.data instanceof FileTaskInfo &&tg_event.dataEx instanceof FileInfo){
                    FileInfo fileInfo = (FileInfo) tg_event.dataEx;
                    String ids = ((FileTaskInfo)tg_event.data).id;
                    if(!TextUtils.isEmpty(ids)&&ids.contains("_")) {
                        String[] idArray = ids.split("_");
                        if(idArray.length > 1){
                            for(int i = 0; i<((CircleHomeAdapter)mAdapter).getRealItemCount();i++){
                                MultiItemEntity multiItemEntity = mAdapter.getItem(i);
                                if(multiItemEntity!=null&&multiItemEntity instanceof BlogInfo){
                                    BlogInfo blogInfo = (BlogInfo) multiItemEntity;
                                    boolean isVideoDownedd = blogInfo.isVideoDownloadEnough();

                                    if(idArray[1].equals(String.valueOf(blogInfo.id))){
                                        switch (tg_event.event) {
                                            case EUser_Td_Message_Photo_Ok:
                                                blogInfo.updatePhotoFile(fileInfo);
                                                break;
                                            case EUser_Td_Message_Video_Ok:
                                                blogInfo.updateVideoFile(fileInfo);
                                                break;
                                        }
                                        if(tg_event.event == TelegramManager.EUser_TgEvent.EUser_Td_Message_Video_Ok&&isVideoDownedd){
                                            return;
                                        }
                                        mAdapter.notifyItemChanged(i);
                                        break;
                                    }
                                }

                            }
                        }
                    }
                }
                break;
        }
    }
}
